from django.db import transaction
from django.shortcuts import render
from rest_framework import permissions
from rest_framework.views import APIView
from utils.customer_modelviewset import CustomModelViewSet
from utils import response_ok, response_error
from apps.member.diary.models import Diary
from apps.member.category.models import Category
from utils.exception import CustomError
from .serializers import DiarySerializer


# Create your views here.

class DictView(APIView):
    permission_classes = [permissions.IsAdminUser, ]

    def get(self, request):
        ret = {
            'category': [{'code': category.id, 'codeName': category.name} for category in Category.objects.filter()]
        }
        return response_ok(ret)


class DiaryViewSet(CustomModelViewSet):
    permission_classes = [permissions.IsAdminUser, ]
    queryset = Diary.objects.filter(delete=False)
    serializer_class = DiarySerializer

    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                request.data['user'] = self.request.user.id
                super(CustomModelViewSet, self).create(request, *args, **kwargs)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))
        return response_ok()

